import 'package:flutter/material.dart';

class Demo extends StatelessWidget {
  bool checkedState = false;

  Widget getAlertDialog(BuildContext context) {
    print("getAlertDialog");
    return AlertDialog(
      title: Text("提示"),
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text("您确定要删除当前文件吗?"),
          SizedBox(height: 50),
          Row(
            children: <Widget>[
              Text("整个Dialog都会渲染"),
              Checkbox(
                // 依然使用Checkbox组件
                value: checkedState,
                onChanged: (bool? value) {
                  // 此时context为对话框UI的根Element，我们
                  // 直接将对话框UI对应的Element标记为dirty
                  // 一句神奇的代码, 可以起到setState的效果, 但是context是整个对话框
                  (context as Element).markNeedsBuild();
                  checkedState = !checkedState;
                },
              ),
            ],
          ),
          Row(
            children: [
              Text("缩小context, 只是checkedbox变化"),
              // 这是一种常用的缩小`context`范围的方式
              Builder(
                builder: (BuildContext context) {
                  return Checkbox(
                    value: checkedState,
                    onChanged: (bool? value) {
                      (context as Element).markNeedsBuild();
                      checkedState = value!;
                    },
                  );
                },
              ),
            ],
          )
        ],
      ),
      actions: <Widget>[
        TextButton(
          child: Text("取消"),
          onPressed: () => Navigator.of(context).pop(), // 关闭对话框
        ),
        TextButton(
          child: Text("删除"),
          onPressed: () {
            //关闭对话框并返回true
            Navigator.of(context).pop(checkedState);
          },
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("神奇的 element.markNeedsBuild"),
        //点击该按钮后弹出对话框
        ElevatedButton(
          child: Text("AlertDialog"),
          onPressed: () async {
            //弹出对话框并等待其关闭
            bool? delete = await showDialog<bool>(
              context: context,
              builder: getAlertDialog,
            );

            if (delete == null) {
              print("取消删除");
            } else {
              print("已确认删除。删除子文件：$delete");
              //... 删除文件
            }
          },
        ),
      ],
    );
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(body: Demo()),
  ));
}
